import os
from django.shortcuts import render, HttpResponse
from django.conf import settings
from django import forms
from web.utils.bootstrip import BootstrapForm, BootstrapModelForm
from web import models


def upload_list(request):
    """文件上传"""
    if request.method == "GET":
        return render(request, 'upload_list.html')
    # print(request.POST)  # 请求体中的数据 'username': ['lwl']
    # print(request.FILES)  # 请求发过来的文件  <MultiValueDict: {'avatar': [<InMemoryUploadedFile: 1842350752.jpeg (image/jpeg)>]}>
    file_object = request.FILES.get('avatar')
    print(file_object.name)  # 打印文件名
    # 读取文件
    f = open(file_object.name, mode='wb')
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()

    return HttpResponse("上传成功")


class UploadForm(BootstrapForm):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")


def upload_form(request):
    """Form 混合上传"""
    title = "Form上传"
    if request.method == "GET":
        form = UploadForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})

    # get方式，看到页面；post方式，表单验证
    form = UploadForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 1 读取图片内容，写入到文件夹中并获取文件的路径
        image_object = form.cleaned_data.get('img')

        # media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        media_path = os.path.join("media", image_object.name)

        f = open(media_path, mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 2 将文件路径写入到数据库
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path
        )

        return HttpResponse("上传成功")
    return render(request, 'upload_form.html', {'form': form, 'title': title})


class UploadModalForm(BootstrapModelForm):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = "__all__"


def upload_modal_form(request):
    """MoadlForm 混合上传"""
    title = "ModalForm上传"
    if request.method == "GET":
        form = UploadModalForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})

    form = UploadModalForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        form.save()  # 这句代码对文件会自动保存到模型设置的目录里，字段+上传的路径会写入数据库
        return HttpResponse("上传成功")
    return render(request, 'upload_form.html', {'form': form, 'title': title})
